package com.yaoyanshe.trialfield.network.http

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import java.io.IOException

/**
 *<p>description:</p>
 *<p>created on: 2020/9/20 14:45</p>
 * @author tck
 * @version v1.3.0
 *
 */

data class SytBaseResp<T>(
        var errorCode: Int,
        var subCode: Int,
        var status: Int,
        var errorMessage: String,
        var subMessage: String,
        var data: T? = null,
)


suspend fun <T : Any> SytBaseResp<T>.doSuccess(successBlock: (suspend CoroutineScope.(T?) -> Unit)? = null): SytBaseResp<T> {
    return coroutineScope {
        if (status == 0) successBlock?.invoke(this, this@doSuccess.data)
        this@doSuccess
    }

}

suspend fun <T : Any> SytBaseResp<T>.doError(errorBlock: (suspend CoroutineScope.(String) -> Unit)? = null): SytBaseResp<T> {
    return coroutineScope {
        if (errorCode != 0) {
            when {
                this@doError.errorMessage.isNotEmpty() -> {
                    errorBlock?.invoke(this, this@doError.errorMessage)
                }
                this@doError.subMessage.isNotEmpty() -> {
                    errorBlock?.invoke(this, this@doError.subMessage)
                }
                else -> {
                    errorBlock?.invoke(this, this@doError.errorMessage)
                }
            }
        }
        this@doError
    }
}


fun <T : Any> SytBaseResp<T>.convertData(): T? {
    return data
}